package cn.yh.register.hosp.api;

import cn.yh.register.common.exception.RegisterException;
import cn.yh.register.common.helper.HttpRequestHelper;
import cn.yh.register.common.result.Result;
import cn.yh.register.common.result.ResultCodeEnum;
import cn.yh.register.hosp.service.DepartmentService;
import cn.yh.register.hosp.service.HospitalService;
import cn.yh.register.hosp.service.HospitalSetService;
import cn.yh.register.hosp.service.ScheduleService;
import cn.yh.register.model.hosp.Department;
import cn.yh.register.model.hosp.Hospital;
import cn.yh.register.model.hosp.Schedule;
import cn.yh.register.vo.hosp.*;
import cn.yh.register.vo.order.SignInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Api(tags = "数据上传")
@RestController
@RequestMapping("/api/hosp")
public class HospitalApiController {

    @Autowired
    HospitalService hospitalService;

    @Autowired
    HospitalSetService hospitalSetService;

    @Autowired
    DepartmentService departmentService;

    @Autowired
    ScheduleService scheduleService;

    @ApiOperation("上传医院")
    @PostMapping("/saveHospital")
    public Result<?> saveHospital(HttpServletRequest request) {
        //处理参数 & 校验结果
        Map<String, Object> objectMap = this.handleParam(request);
        //调用service
        hospitalService.saveHospital(objectMap);
        return Result.ok();
    }

    @ApiOperation("获取医院信息")
    @PostMapping("/hospital/show")
    public Result<?> hospital(HttpServletRequest request) {
        //处理参数 & 校验结果
        Map<String, Object> objectMap = this.handleParam(request);
        //调service
        Hospital hospital = hospitalService.getByHoscode(((String) objectMap.get("hoscode")));
        return Result.ok(hospital);
    }

    @ApiOperation("分页查询医院列表")
    @GetMapping("/{page}/{limit}")
    public Result<Page<Hospital>> index(@PathVariable Integer page,
                                        @PathVariable Integer limit,
                                        HospitalQueryVo hospitalQueryVo) {
        Page<Hospital> hospitals = hospitalService.selectPage(page, limit, hospitalQueryVo);
        return Result.ok(hospitals);

    }

    @ApiOperation("根据医院名称模糊查询")
    @GetMapping("/findByHosname/{hosname}")
    public Result<List<Hospital>> findByHosname(@PathVariable String hosname) {
        List<Hospital> byHosname = hospitalService.findByHosname(hosname);
        return Result.ok(byHosname);
    }

    /**
     * 处理参数 & 校验结果
     *
     * @param request 请求 对象
     * @return
     */
    private Map<String, Object> handleParam(HttpServletRequest request) {
        //接收参数
        Map<String, String[]> map = request.getParameterMap();
        //转Map
        Map<String, Object> objectMap = HttpRequestHelper.switchMap(map);
        //接收的参数中“+”被替换成“ ”，为避免签名校验失败，我们需要将“+”再替换回去
        String logoData = (String) objectMap.get("logoData");
        if (!StringUtils.isEmpty(logoData)) {
            logoData = logoData.replaceAll(" ", "+");
            objectMap.put("logoData", logoData);
        }
        String hoscode = (String) objectMap.get("hoscode");
        if (hoscode == null) {
            throw new RegisterException(ResultCodeEnum.PARAM_ERROR);
        }
        //获取签名Key
        String signKey = hospitalSetService.getSignKey(hoscode);
        //校验签名
        if (!HttpRequestHelper.isSignEquals(objectMap, signKey)) {
            throw new RegisterException(ResultCodeEnum.SIGN_ERROR);
        }
        return objectMap;
    }

    @ApiOperation("上传科室")
    @PostMapping("saveDepartment")
    public Result<?> saveDepartment(HttpServletRequest request) {
        //处理参数
        Map<String, Object> objectMap = this.handleParam(request);
        //调service
        departmentService.saveDepartment(objectMap);
        return Result.ok();
    }

    @ApiOperation("分页查询科室列表")
    @PostMapping("department/list")
    public Result<Page<Department>> departmentList(HttpServletRequest request) {
        //处理参数 & 校验签名
        Map<String, Object> objectMap = this.handleParam(request);
        //页码
        Integer page = StringUtils.isEmpty(objectMap.get("page")) ? 1 : Integer.parseInt((String) objectMap.get("page"));
        //每页条数
        Integer limit = StringUtils.isEmpty(objectMap.get("limit")) ? 1 : Integer.parseInt((String) objectMap.get("limit"));
        //查询条件
        DepartmentQueryVo queryVo = new DepartmentQueryVo();
        queryVo.setHoscode((String) objectMap.get("hoscode"));

        //掉service
        Page<Department> departmentPage = departmentService.findDeptList(page, limit, queryVo);

        return Result.ok(departmentPage);
    }

    @ApiOperation("删除科室信息")
    @PostMapping("department/remove")
    public Result<?> removeSchedule(HttpServletRequest request) {
        Map<String, Object> objectMap = this.handleParam(request);
        departmentService.remove((String) objectMap.get("hoscode"), (String) objectMap.get("depcode"));
        return Result.ok();
    }

    @ApiOperation("上传排班")
    @PostMapping("saveSchedule")
    public Result<?> saveSchedule(HttpServletRequest request) {
        Map<String, Object> objectMap = this.handleParam(request);
        scheduleService.save(objectMap);
        return Result.ok();
    }

    @ApiOperation("分页查询排班列表")
    @PostMapping("schedule/list")
    public Result<Page<Schedule>> scheduleList(HttpServletRequest request) {
        //处理参数 & 校验签名
        Map<String, Object> objectMap = this.handleParam(request);
        //页码
        Integer page = StringUtils.isEmpty(objectMap.get("page")) ? 1 : Integer.parseInt((String) objectMap.get("page"));
        //每页条数
        Integer limit = StringUtils.isEmpty(objectMap.get("limit")) ? 1 : Integer.parseInt((String) objectMap.get("limit"));

        ScheduleQueryVo scheduleQueryVo = new ScheduleQueryVo();
        scheduleQueryVo.setHoscode((String) objectMap.get("hoscode"));
        scheduleQueryVo.setDepcode((String) objectMap.get("depcode"));
        Page<Schedule> schedulePage = scheduleService.selectPage(page, limit, scheduleQueryVo);
        return Result.ok(schedulePage);
    }


    @ApiOperation("删除排班")
    @PostMapping("schedule/remove")
    public Result<?> scheduleRemove(HttpServletRequest request) {
        Map<String, Object> objectMap = this.handleParam(request);
        scheduleService.remove((String) objectMap.get("hoscode"), (String) objectMap.get("hosScheduleId"));
        return Result.ok();
    }

    @ApiOperation("查询医院详情")
    @GetMapping("/{hoscode}")
    public Result<Map<String, Object>> item(@ApiParam(name = "hoscode", value = "医院code", required = true)
                                            @PathVariable String hoscode) {
        Map<String, Object> item = hospitalService.item(hoscode);
        return Result.ok(item);
    }

    @ApiOperation("获取科室列表")
    @GetMapping("/department/{hoscode}")
    public Result<List<DepartmentVo>> findDeptList(@ApiParam(name = "hoscode", value = "医院code", required = true)
                                                   @PathVariable String hoscode) {
        List<DepartmentVo> deptTree = departmentService.findDeptTree(hoscode);
        return Result.ok(deptTree);
    }

    @ApiOperation("获取可预约的排班数据")
    @GetMapping("/auth/getBookingScheduleRule/{page}/{limit}/{hoscode}/{depcode}")
    public Result<Map<String, Object>> getBookingSchedule(@ApiParam(name = "page", value = "当前页码", required = true)
                                                          @PathVariable("page") Integer page,
                                                          @ApiParam(name = "limit", value = "每页记录数", required = true)
                                                          @PathVariable Integer limit,
                                                          @ApiParam(name = "hoscode", value = "医院code", required = true)
                                                          @PathVariable String hoscode,
                                                          @ApiParam(name = "depcode", value = "科室code", required = true)
                                                          @PathVariable String depcode) {
        Map<String, Object> bookingScheduleRule = scheduleService.getBookingScheduleRule(page, limit, hoscode, depcode);
        return Result.ok(bookingScheduleRule);
    }

    @ApiOperation("获取某天的排班数据")
    @GetMapping("/auth/findScheduleList/{hoscode}/{depcode}/{workDate}")
    public Result<List<Schedule>> findScheduleList(@ApiParam(name = "hoscode", value = "医院code", required = true)
                                                   @PathVariable String hoscode,
                                                   @ApiParam(name = "depcode", value = "科室code", required = true)
                                                   @PathVariable String depcode,
                                                   @ApiParam(name = "workDate", value = "排班日期", required = true)
                                                   @PathVariable String workDate) {
        List<Schedule> scheduleList = scheduleService.getScheduleList(hoscode, depcode, workDate);
        return Result.ok(scheduleList);
    }


    @ApiOperation(value = "根据排班id获取排班数据")
    @GetMapping("/getSchedule/{scheduleId}")
    public Result getSchedule(
            @ApiParam(name = "scheduleId", value = "排班id", required = true)
            @PathVariable String scheduleId) {
        return Result.ok(scheduleService.getById(scheduleId));
    }


    @ApiOperation("获取下单所需要的排班数据")
    @GetMapping("/inner/getScheduleOrderVo/{scheduleId}")
    public ScheduleOrderVo getScheduleOrderVo(@PathVariable String scheduleId){
        return scheduleService.getScheduleOrder(scheduleId);
    }
    @ApiOperation("获取签名信息")
    @GetMapping("/inner/getSignInfoVo/{hoscode}")
    public SignInfoVo getSignInfoVo(@PathVariable String hoscode){
        return hospitalSetService.getSignInfoVo(hoscode);
    }

}
